<?php

namespace core;

use \PDO, \PDOStatement, \PDOException;

class Dao
{
    private $pdo;           //用于保存pdo返回对象
    private $fetch_mode;     //用于获取数据库返回数据格式
    public function __construct($database = array(), $dirvers = array())     //database用于保存数据库连接数据，drivers用于传入驱动
    {
        $type = $database['type'] ?? 'mysql';
        $host = $database['host'] ?? 'localhost';
        $port = $database['port'] ?? '3306';
        $user = $database['user'] ?? 'root';
        $pass = $database['pass'] ?? 'root';
        $dbname = $database['dbname'] ?? 'myblog';
        $charset = $database['charset'] ?? 'utf8';

        // 设置默认返回数据格式
        $this->fetch_mode = $dirvers[PDO::ATTR_DEFAULT_FETCH_MODE] ?? PDO::FETCH_ASSOC;
        // 设置默认错误处理模式
        $dirvers[PDO::ATTR_ERRMODE] = $dirvers[PDO::ATTR_ERRMODE] ?? PDO::ERRMODE_EXCEPTION;

        // 连接数据库
        try {

            $this->pdo = @new PDO($type . ':dbname=' . $dbname . ';host=' . $host . ';port=' . $port, $user, $pass, $dirvers);
        } catch (PDOException $e) {
            $this->dao_exception($e);
        }
        // 设置字符集
        try {
            $this->pdo->exec("set names {$charset}");
        } catch (PDOException $e) {
            $this->dao_exception($e);
        }
    }
    //异常处理方法
    private function dao_exception($e)
    {
        echo 'SQL执行错误！<br/>';
        echo '错误文件为：' . $e->getFile() . '<br/>';
        echo '错误行号为：' . $e->getLine() . '<br/>';
        echo '错误描述为：' . $e->getMessage();
        die();
    }
    // 写操作
    public function dao_exec($sql)
    {
        try {
            return $this->pdo->exec($sql);
        } catch (PDOException $e) {
            $this->dao_exception($e);
        }
    }
    // 获取自增长id
    public function dao_insert_id()
    {
        return $this->pdo->lastInsertId();
    }
    // 读操作
    public function dao_query($sql, $all = false)
    {
        try {
            $stmt = $this->pdo->query($sql);

            // 设置fetch——mode
            $stmt->setFetchMode($this->fetch_mode);
            if (!$all) {
               return $stmt->fetch();
            } else {
               return $stmt->fetchAll();
            }
        } catch (PDOException $e) {
            $this->dao_exception($e);
        }
    }
}
